<template>
    <div class="table-page">
        <div class="table-search-box" @keyup.enter="search()">
            <div class="search-item">
                <label>角色名：</label>
                <div class="table-query-input">
                    <el-input
                        v-model="queryData.name"
                        clearable
                        placeholder="角色名"
                    ></el-input>
                </div>
            </div>
            <div class="search-item">
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    :loading="tableLoading"
                    @click="clickSearch()"
                    >搜索
                </el-button>
            </div>
            <div class="search-item">
                <el-button
                    icon="el-icon-refresh"
                    :loading="tableLoading"
                    @click="resetSearch()"
                    >重置
                </el-button>
            </div>
        </div>
        <div class="table-operation-box">
            <el-button
                type="primary"
                style="margin-bottom: 2em"
                icon="el-icon-plus"
                @click="clickAdd('添加角色', selectAllAction)"
                >新增角色
            </el-button>
        </div>
        <div class="table-data-box">
            <el-table
                ref="table"
                v-loading="tableLoading"
                :data="tableData"
                border
                style="width: 100%;min-height:40em"
                row-key="id"
            >
                <el-table-column prop="id" label="角色code" width="120">
                </el-table-column>
                <el-table-column
                    prop=""
                    label="角色类型"
                    width="260"
                    align="center"
                >
                    <template slot-scope="scope">
                        <k-tag
                            :tag="
                                scope.row.system ? status.system : status.input
                            "
                        ></k-tag>
                    </template>
                </el-table-column>

                <el-table-column prop="name" label="角色名" min-width="100">
                </el-table-column>

                <el-table-column prop="remark" label="备注" min-width="100">
                </el-table-column>
                <el-table-column
                    prop="actionCount"
                    label="拥有action数量"
                    width="100"
                >
                </el-table-column>
                <el-table-column label="操作" width="200" align="center">
                    <template slot-scope="scope">
                        <el-button
                            class="primary"
                            type="text"
                            size="mini"
                            icon="el-icon-edit"
                            :loading="scope.row.opLoading"
                            @click="
                                clickSimpleEdit(
                                    scope.row,
                                    '角色编辑',
                                    openEditRole(scope.row)
                                )
                            "
                            >编辑
                        </el-button>
                        <el-button
                            v-if="
                                !scope.row.system && scope.row.actionCount === 0
                            "
                            type="text"
                            size="mini"
                            class="danger"
                            icon="el-icon-delete"
                            :loading="scope.row.opLoading"
                            @click="
                                tableDelete(
                                    '/user/cu/auth/role/delete',
                                    {
                                        id: scope.row.id
                                    },
                                    true,
                                    () => removeLineData(scope.row)
                                )
                            "
                            >删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div v-if="pageData.total" class="xy-between table-page-box"></div>
        <el-dialog
            :title="dialogFormTitle"
            :visible.sync="dialogFormVisible"
            custom-class="two-dialog"
        >
            <el-form
                ref="dataForm"
                :model="dataForm"
                label-width="6em"
                :rules="dataFormRule"
                class="table-edit-from"
            >
                <div class="xy-between al-start">
                    <div>
                        <el-form-item label="角色code" prop="id">
                            <el-input
                                v-model="dataForm.id"
                                :disabled="
                                    dataForm.system || !dataForm.addAction
                                "
                            ></el-input>
                        </el-form-item>

                        <el-form-item label="角色名" prop="name">
                            <el-input
                                v-model="dataForm.name"
                                :disabled="dataForm.system"
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="展示级别" >
                            <el-select
                                v-model="dataForm.showLevel"
                                placeholder="请选择"
                            >
                                <el-option
                                    v-for="item in Object.keys(showLevel)"
                                    :key="item"
                                    :label="showLevel[item].desc"
                                    :value="item"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="备注" prop="remark">
                            <el-input
                                v-model="dataForm.remark"
                                :disabled="dataForm.system"
                                type="textarea"
                                :autosize="{ minRows: 2, maxRows: 4 }"
                            ></el-input>
                        </el-form-item>
                    </div>
                    <div>
                        <el-input
                            v-model="actionSearch"
                            placeholder="action关键字搜索"
                        >
                        </el-input>
                        <el-tree
                            v-if="dataForm && dataForm.id !== undefined"
                            :key="dataForm.id"
                            ref="tree"
                            :data="actions"
                            :default-checked-keys="dataForm.actionCodes"
                            show-checkbox
                            node-key="id"
                            default-expand-all
                            :check-strictly="true"
                            :props="{ children: 'children', label: 'name' }"
                            :filter-node-method="filterAction"
                            @check-change="clickSelectAction"
                        >
                            <span
                                slot-scope="{ node }"
                                class="custom-tree-node"
                            >
                                <span>{{ node.label }}</span>
                            </span>
                        </el-tree>
                    </div>
                </div>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button :loading="submitFlag" @click="dialogClose"
                    >取 消</el-button
                >
                <el-button
                    :loading="submitFlag"
                    type="primary"
                    @click="formDataSave('/user/cu/auth/role/update')"
                    >保 存</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { fetchAllAction, fetchRoleAllActionCode } from "@/api/user.js";
import { TablePage } from "@/layout/mixin/iVue.js";
import { mapState } from "vuex";
import { treeList2Tree } from "@/utils/index.js";
import { post, put } from "@/api/request";

export default {
    name: "RoleNameSetting",
    components: {},
    mixins: [TablePage],
    data() {
        return {
            queryData: {
                searchCount: true,
                size: 1000
            },
            initAddForm: {
                id: null,
                name: null,
                remark: null,
                actionCodes: []
            },
            actions: null,
            actionSearch: null,
            dataFormRule: {
                id: [
                    {
                        required: true,
                        message: "请输入角色code",
                        trigger: "change"
                    }
                ],
                name: [
                    {
                        required: true,
                        message: "请输入角色名",
                        trigger: "change"
                    }
                ]
            }
        };
    },
    computed: {
        ...mapState({
            status: state => state.status.roleSystem,
            showLevel: state => state.status.showLevel,
        })
    },
    watch: {
        actionSearch(val) {
            this.$refs.tree.filter(val);
        }
    },
    methods: {
        search(queryData) {
            this.loadTable("/user/cu/auth/role/s-list", queryData);
        },
        openEditRole(data) {
            return () => {
                return Promise.all([
                    this.selectAllAction(),
                    this.loadRoleActions(data)
                ]);
            };
        },
        async selectAllAction() {
            if (this.actions) {
                return;
            }
            return fetchAllAction({ size: 1000 }).then(actions => {
                console.log("action");
                this.actions = treeList2Tree(actions);
            });
        },
        async loadRoleActions(roleData) {
            console.log("loadRoleActions");
            if (roleData.actionCodes) {
                return;
            }
            return fetchRoleAllActionCode({ roleCode: roleData.id }).then(
                res => {
                    this.$set(roleData, "actionCodes", res);
                }
            );
        },
        filterAction(value, data) {
            if (!value) return true;
            return data.name.indexOf(value) !== -1;
        },
        clickSelectAction(data, checked, indeterminate) {

            const actionCode = data.id;
            if (checked) {
                console.log("checked",data)
                this.checkItem(data);
            } else {
                this.unSelectItem(data);
            }
        },
        parentItem(data) {
            let parent = data.parent;
            if (parent) {
                this.parentItem(parent);
                let actionCode = parent.id;
                if (this.dataForm.actionCodes.includes(actionCode)) {
                    return;
                }
                this.dataForm.actionCodes.push(actionCode);
            }
        },
        checkItem(data) {
            let actionCode = data.id;
            if (this.dataForm.actionCodes.includes(actionCode)) {
                return;
            }
            this.parentItem(data);
            this.dataForm.actionCodes.push(actionCode);
            for (let child of data.children || []) {
                this.checkItem(child);
            }
            console.log(this.dataForm.actionCodes)
            this.$refs.tree.setCheckedKeys(this.dataForm.actionCodes);
        },
        unSelectItem(data) {
            let actionCode = data.id;
            this.dataForm.actionCodes.splice(
                this.dataForm.actionCodes.indexOf(actionCode),
                1
            );
            for (let child of data.children || []) {
                this.unSelectItem(child);
            }
            this.$refs.tree.setCheckedKeys(this.dataForm.actionCodes);
        }
    }
};
</script>

<style lang="scss" scoped></style>
